<template>
  <div class="pl-form-designer">
    <tool @preview= "preview()" @ShowForm= "ShowForm()" @dataFormSubmit="dataFormSubmit()" :fullName="fullName"></tool>
    <div class="main">
       <div class="container" ref="generator">
          <menu-list></menu-list>
          <draw :formConf = formConf></draw>
          <right-panel ref="rightBoard" :allTable="allTable" :databaseid="databaseid" :formConf = formConf :show-field="!!drawingList.length" @tag-change="tagChange"></right-panel>
       </div>
    </div>
    <Preview :visible.sync="previewVisible" :form-data="formData" />
    <FormProperties :visible.sync="formProperShow" :formConf = formConf />
  </div>
 
</template>


<script>
import tool from './tool/index';
import FormProperties from './formProperties';
import menuList from './menu/index';
import draw from './draw/index';
import rightPanel from './rightPanel/index'; 
import Preview from './perview'
import mixin from '@/mixins/form'
import { noVModelList } from '@/generator/comConfig'
import {
  formConf
} from '@/generator/config'
import {
  deepClone, getUrlParameter
} from '@/utils/formIndex'
import { mapState } from 'vuex';
import formDesignerMixin from '@/mixins/formDesigner'
import DevFormServiceApi from '@/service/dev/DevFormService'

export default {
  mixins: [formDesignerMixin],
  mixins: [mixin],
  provide() {
      return {
        getShowType: () => this.showType
      }
    },
  data(){
    return{
      formConf: deepClone(formConf), 
      showType: 'pc',
      previewVisible: false,
      id:"",
      fullName:'',
      allTable: [],
      databaseid: '',
      formProperShow: false,
    }
  },
  created(){
    // this.init();
    this.id = this.$route.query.id
    this.init()
    sessionStorage.setItem("urlParams", JSON.stringify(getUrlParameter()))
  },
  methods:{
    
    async init() {
      // console.log(this.$route)
      this.id = this.$route.query.id
      let params = {
        id: this.id,
      }
      let res = await DevFormServiceApi.queryById(params)
      this.fullName = res.data.fullName
      this.databaseid = res.data.dbLinkId
      this.allTable = JSON.parse(res.data.temTable)
      console.log(this.allTable,'this.allTable')
      let subtable = this.allTable.filter(o=>o.typeId == 2)
      this.$store.commit('designer/setSubTable', subtable)
      let formData = JSON.parse(res.data.formData)
      if (typeof formData === 'object' && formData !== null) {
        this.isDrawingListChange = false
        for(var i=0;i<formData.fields.length;i++){
          this.$store.commit('designer/setDrawingList', formData.fields[i])
        }
        // this.drawingList = deepClone(this.formData.fields)
        Object.assign(this.formConf, formData)
        // this.idGlobal = this.formConf.idGlobal
        this.$store.commit('designer/setIdGlobal', this.formConf.idGlobal)
        // if (this.drawingList.length) this.activeFormItem(this.drawingList[0])
        if (this.drawingList.length){
          this.$store.commit('designer/setActiveData', this.drawingList[0])
          this.$store.commit('designer/setActiveId', this.drawingList[0].config.formId)
        }
        console.log(this.drawingList[0],'activeData')
        
        // this.$refs.rightBoard.setDefaultOptions(this.drawingList[0].config.tableName, this.databaseid)

      } else {
        this.drawingList = []
        this.idGlobal = 100
      }
      console.log(formData,'formData')
    },
    preview() {
      this.AssembleFormData()
      this.previewVisible = true
    },
    ShowForm() {
      this.formProperShow = true;
    },
    dataFormSubmit() {
      let boo = false
      if (!this.drawingList.length) {
          // reject({ msg: '表单不允许为空', target: 1 })
          this.$message({ message: '表单不允许为空',type: 'warning' });
          return
        }
        const loop = list => {
          for (let i = 0; i < list.length; i++) {
            const e = list[i]
            const config = e.config
            if(config.tableName == '') {
              this.$message({ message: `${config.label}的数据库表不能为空`,type: 'warning' });
              boo = true
              break
            }
            if (config.layout === "colFormItem" && !noVModelList.includes(config.pfKey) && !e.vModel) {
              this.$message({ message: `${config.label}的控件字段不能为空`,type: 'warning' });
              boo = true
              break
            }
            if (e.config.isStorage == 2 && !e.vModel) {
              this.$message({ message: `${config.label}的控件字段不能为空`,type: 'warning' });
              boo = true
              break
            }
            if (config.pfKey === 'billRule') {
              if (!config.rule) {
                this.$message({ message: `单据组件“单据模板”属性为必填项`,type: 'warning' });
                boo = true
                break
              }
            }
            if (config.pfKey === 'relationForm') {
              if (!e.modelId) {
                this.$message({ message: `关联表单控件“关联功能”属性为必填项`,type: 'warning' });
                boo = true
                break
              }
              if (!e.relationField) {
                this.$message({ message: `关联表单控件“显示字段”属性为必填项`,type: 'warning' });
                boo = true
                break
              }
            }
            if (config.pfKey === 'popupSelect') {
              if (!e.interfaceId) {
                this.$message({ message: `弹窗选择控件“远端数据”属性为必填项`,type: 'warning' });
                boo = true
                break
              }
              if (!e.propsValue) {
                this.$message({ message: `弹窗选择控件“储存字段”属性为必填项`,type: 'warning' });
                boo = true
                break
              }
              if (!e.relationField) {
                this.$message({ message: `弹窗选择控件“显示字段”属性为必填项`,type: 'warning' });
                boo = true
                break
              }
            }
            if (config.pfKey === 'popupTableSelect') {
              if (!e.interfaceId) {
                this.$message({ message: `下拉表格控件“远端数据”属性为必填项`,type: 'warning' });
                boo = true
                break
              }
              if (!e.propsValue) {
                this.$message({ message: `下拉表格控件“储存字段”属性为必填项`,type: 'warning' });
                boo = true
                break
              }
              if (!e.relationField) {
                this.$message({ message: `下拉表格控件“显示字段”属性为必填项`,type: 'warning' });
                boo = true
                break
              }
            }
            if (config.layout === 'rowFormItem' && !config.children.length) {
              this.$message({ message: `您的${config.label}控件中没有组件`,type: 'warning' });
              boo = true
              break
            }
            if (config && config.children && Array.isArray(config.children)) {
              loop(config.children)
            }
          }
        }
        loop(this.drawingList)
        if(boo) return
      this.AssembleFormData()
      this.submit();
    },
    async submit() {
      let data = this.$store.state.designer.formData
      data.idGlobal = this.$store.state.designer.idGlobal
      let params = {
        formData: JSON.stringify(data),
        id: this.id
      }

      let res = await DevFormServiceApi.save(params)
      if(res.status === 200) {
        this.$message({message: '保存成功', type:'success'})
      }
    },

    AssembleFormData() {
      this.$store.state.designer.formData = {
        ...this.formConf,
        fields: deepClone(this.drawingList),
      }
    },
    tagChange(newTag) {
      newTag = this.cloneComponent(newTag)
      const config = newTag.config
      newTag.vModel = this.activeData.vModel
      config.formId = this.activeId
      console.log(config.formId,'config.formId')
      config.span = this.activeData.config.span
      this.activeData.config.tag = config.tag
      this.activeData.config.tagIcon = config.tagIcon
      this.activeData.config.document = config.document
      if (typeof this.activeData.config.defaultValue === typeof config.defaultValue) {
        config.defaultValue = this.activeData.config.defaultValue
      }
      Object.keys(newTag).forEach(key => {
        if (this.activeData[key] !== undefined) {
          newTag[key] = this.activeData[key]
        }
      })
      this.activeData = newTag
      this.updateDrawingList(newTag, this.drawingList)
    },
    updateDrawingList(newTag, list) {
      const index = list.findIndex(item => item.config.formId === this.activeId)
      if (index > -1) {
        list.splice(index, 1, newTag)
      } else {
        list.forEach(item => {
          if (Array.isArray(item.config.children)) this.updateDrawingList(newTag, item.config.children)
        })
      }
    },
  },
  computed: {
   ...mapState('designer',["drawingList", "formData"])
 },
  components:{
    tool,
    menuList,
    rightPanel,
    draw,
    Preview,
    FormProperties
  }
}
</script>

<style>

</style>